package com.syxbyi._3tcp;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

// 客户端应该一边等待接收用户输入，一边接收服务器端信息，所以应该使用多线程
// 由于跟client对接的服务器端线程只有一个，所以只需要一个接收线程
public class ChatClient2 {

    private final User user;

    public ChatClient2(String name) {
        this.user = new User(name);
        run();
    }

    // 主线程接收用户输入，并发送给服务器
    public void run() {
        Socket socket = null;
        PrintStream printStream = null;
        Thread listener = null;
        Scanner scanner = new Scanner(System.in);
        try {
            socket = new Socket("127.0.0.1", 6666);
            // 开始监听
            listener = new Thread(new ChatClientListener(user, socket));
            listener.start();
            printStream = new PrintStream(socket.getOutputStream());
            // 首先向服务器端发送用户信息
            System.out.printf("用户%s上线\n", user.getName());
            printStream.println(user.getName());
            // 不断读取用户输入并发送
            while(true) {
                System.out.printf("%s> ", user.getName());
                String msg = scanner.nextLine();
                // 用户手动退出客户端
                if (Command.isGoodbyeCommand(msg)) {
                    printStream.println(Command.getGoodbyeCommand());
                    break;
                }
                if (msg != null) {
                    printStream.println(msg);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭监听
            if (listener != null) {
                listener.interrupt();
            }
            if (printStream != null) {
                printStream.close();
            }
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.printf("用户%s下线\n", user.getName());
    }

    public static void main(String[] args) {
        if (args.length != 0) {
            new ChatClient2(args[0]);
        } else {
            new ChatClient2("Jack");
        }
    }

}
